import { useState, useEffect, useRef, useContext } from 'react';
import { Tabs, List, SearchBar, Empty, Toast, InfiniteScroll } from 'antd-mobile';
import { SearchBarRef } from 'antd-mobile/es/components/search-bar'
import { SearchOutline } from 'antd-mobile-icons';
import { useHistory } from "react-router-dom";
import xss from 'xss';
import moment from 'moment';

import { MySdkStoreContext } from '../../../context';
import { SearchTypes, searchApi } from './config';

import './style.scss';
import AvatarImage from '../../../components/AvatarImage';

export default function() {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const searchRef = useRef<SearchBarRef>(null)
  const [keyword, setKeyword] = useState('');
  const [result, setResult] = useState({});
  const [pagination, setPagination] = useState({});
  const [tabKey, setTabKey] = useState('all');

  useEffect(() => {
    if (searchRef?.current) {
      searchRef.current.focus();
    }
  }, [searchRef])

  const handleTabChange = (tabKey) => {
    setTabKey(tabKey);
    handleSearch(1, tabKey);
  }

  const handleSearch = async (pageIndex, searchType = tabKey) => {
    if (!keyword) {
      return;
    }

    try {
      const respend = await mySdkStore.sdk[searchApi[searchType]]({ searchKey: keyword, pageIndex, sessionType: 'group' });
      if (searchType === 'all') {
        setResult(respend);
      } else {
        const { rows = [], totalPage } = respend;
        const userRows = SearchTypes.USER === searchType ? rows : [];
        const groupRows = SearchTypes.GROUP === searchType ? rows : [];
        const messageRows = SearchTypes.MESSAGE === searchType ? rows : [];
        setResult({
          [SearchTypes.USER]: pageIndex === 1 ? userRows : [...(result[SearchTypes.USER] || []), ...userRows],
          [SearchTypes.GROUP]: pageIndex === 1 ? groupRows : [...(result[SearchTypes.GROUP] || []), ...groupRows],
          [SearchTypes.MESSAGE]: pageIndex === 1 ? messageRows : [...(result[SearchTypes.MESSAGE] || []), ...messageRows],
        });
        setPagination({ [searchType]: { pageIndex, totalPage } });
      }
    } catch(e: any) {
      Toast.show(e.errorMessage || '操作失败');
    }
  }

  const getNextData = async () => {
    await handleSearch(pagination[tabKey]?.pageIndex + 1);
  }

  const handleSearchCancel = () => {
    if (keyword) {
      setKeyword('');
    } else {
      history.goBack();
    }
  }

  const createConversation = (userId) => {
    mySdkStore.sdk.createConversation({ type: 'single', subUserId: userId }).then((data) => {
      history.push({ pathname: `/chatDetail/${data.cid}` });
    }, () => {
      Toast.show('操作失败')
    });
  }

  const emptyTip = <div className="emptyTipArea">
    {/* <div className="emptyIcon">todo: icon</div> */}
    <Empty />
    请输入关键词进行搜索
  </div>

  return (<div className="globalSearchPage">
    <SearchBar ref={searchRef} placeholder="搜索" onChange={val => setKeyword(val)} onSearch={() => handleSearch(1)} onCancel={handleSearchCancel} showCancelButton style={{ margin: '0 12px 12px 12px', background: '#fff' }} />
    <Tabs onChange={handleTabChange} className="pageTab" activeKey={tabKey}>
      <Tabs.Tab title='全部' key='all'>
        { (!keyword || !Object.keys(result).length) ? emptyTip :
        <>
        {!!result[SearchTypes.USER]?.length &&
        <List header="联系人" style={{ '--border-top': 0, '--border-bottom': 0, '--align-items': 'top', margin: '12px 0', background: '#fff' }}>
          {(result[SearchTypes.USER].filter((_, index) => index < 3) || []).map(item =>
            <List.Item
              key={item.member?.userId}
              prefix={
                <AvatarImage
                  src={item.member?.avatarUrl}
                  nickName={item.member?.nickName}
                  userName={item.member?.userName}
                  userId={item.member?.userId}
                  style={{ marginTop: 12, borderRadius: 8 }}
                  fit='cover'
                  width={42}
                  height={42}
                />}
              description={`ID: ${item.member?.userId}`}
            >
              <div className="userName" onClick={() => createConversation(item.member.userId)}>{item.member.userName || item.member.nickName}</div>
            </List.Item>
            )}
            {result[SearchTypes.USER].length > 3 &&
            <List.Item>
              <a onClick={() => handleTabChange(SearchTypes.USER)}><SearchOutline style={{ marginRight: 12, fontSize: 20 }} /> 查看更多</a>
            </List.Item>
            }
        </List>
        }
        {!!result[SearchTypes.GROUP]?.length &&
        <List header="我的群组" style={{ '--border-top': 0, '--border-bottom': 0, margin: '12px 0', background: '#fff' }}>
          {(result[SearchTypes.GROUP].filter((_, index) => index < 3) || []).map(item => {
            return <List.Item
                key={item.sid}
                prefix={<AvatarImage
                src={item.member?.avatarUrl}
                groupName={item.sessionName}
                style={{ borderRadius: 8 }}
                fit='cover'
                width={42}
                height={42}
              />}
              description={item.memberCount}
            ><span className="searchContent" dangerouslySetInnerHTML={{ __html: xss(item.sessionName) }} onClick={() => history.push(`/chatDetail/${item.sid}`)}></span></List.Item>
          })}
          {result[SearchTypes.GROUP].length > 3 &&
          <List.Item key="more">
            <a onClick={() => handleTabChange(SearchTypes.GROUP)}><SearchOutline style={{ marginRight: 12, fontSize: 20 }} /> 查看更多</a>
          </List.Item>
          }
        </List>
        }
        {!!result[SearchTypes.MESSAGE]?.length &&
        <List header="聊天记录" style={{ '--border-top': 0, '--border-bottom': 0, margin: '12px 0', background: '#fff' }}>
          {(result[SearchTypes.MESSAGE].filter((_, index) => index < 3) || []).map(item => {
              return <List.Item
                key={item.msgId}
                prefix={
                  <AvatarImage
                  src={item.from?.avatarUrl}
                  nickName={item.from?.nickName}
                  userName={item.from?.userName}
                  userId={item.from?.userId}
                  style={{ marginTop: 12, borderRadius: 8 }}
                  fit='cover'
                  width={42}
                  height={42}
                />}
              >
                <div className="briefInfoBar">
                  {item.from?.userName || item.from?.nickName}
                   {/* &gt; 林育 */}
                  <div className="time">{moment(item.timestamp).format('HH:mm')}</div>
                </div>
                <div className="userMessage searchContent" dangerouslySetInnerHTML={{__html: xss(item.searchContent)}} />
              </List.Item>
            })}
            {result[SearchTypes.MESSAGE]?.length > 3 &&
            <List.Item key="more">
              <a onClick={() => handleTabChange(SearchTypes.MESSAGE)}><SearchOutline style={{ marginRight: 12, fontSize: 20 }} /> 查看更多</a>
            </List.Item>
            }
        </List>
        }
        { !result[SearchTypes.USER]?.length && !result[SearchTypes.GROUP]?.length && !result[SearchTypes.MESSAGE]?.length &&
          <div className="adm-infinite-scroll">
            <span>没有更多了</span>
          </div>}
        </>
      }
      </Tabs.Tab>
      <Tabs.Tab title='联系人' key={SearchTypes.USER}>
        <List style={{ '--border-top': 0, '--border-bottom': 0, '--border-inner': 0 }}>
          {(result[SearchTypes.USER] || []).map(item => <List.Item
                key={item.member.userId}
                prefix={
                  <AvatarImage
                    src={item.member?.avatarUrl}
                    nickName={item.member?.nickName}
                    userName={item.member?.userName}
                    userId={item.member?.userId}
                    style={{ marginTop: 12, borderRadius: 8 }}
                    fit='cover'
                    width={42}
                    height={42}
                  />}
                description={`ID: ${item.member.userId}`}
              >
                <div className="userName" onClick={() => createConversation(item.member.userId)}>{item.member.userName || item.member.nickName}</div>
              </List.Item>
            )}
        </List>
        <InfiniteScroll loadMore={getNextData} hasMore={pagination[SearchTypes.USER]?.totalPage > pagination[SearchTypes.USER]?.pageIndex} />
      </Tabs.Tab>
      <Tabs.Tab title='我的群组' key={SearchTypes.GROUP}>
        <List style={{ '--border-top': 0, '--border-bottom': 0, '--border-inner': 0 }}>
          {(result[SearchTypes.GROUP] || []).map(item => {
              return <List.Item
                  key={item.sid}
                  prefix={<AvatarImage
                  src={item.member?.avatarUrl}
                  groupName={item.sessionName}
                  style={{ borderRadius: 8 }}
                  fit='cover'
                  width={42}
                  height={42}
                />}
                description={item.memberCount}
              ><span className="searchContent" dangerouslySetInnerHTML={{ __html: xss(item.sessionName) }} onClick={() => history.push(`/chatDetail/${item.sid}`)}></span></List.Item>
          })}
        </List>
        <InfiniteScroll loadMore={getNextData} hasMore={pagination[SearchTypes.GROUP]?.totalPage > pagination[SearchTypes.GROUP]?.pageIndex} />
      </Tabs.Tab>
      <Tabs.Tab title='聊天记录' key={SearchTypes.MESSAGE}>
        <List style={{ '--border-top': 0, '--border-bottom': 0, '--border-inner': 0 }}>
          {(result[SearchTypes.MESSAGE] || []).map(item => {
            return <List.Item
              key={item.msgId}
              prefix={
                <AvatarImage
                src={item.from?.avatarUrl}
                nickName={item.from?.nickName}
                userName={item.from?.userName}
                userId={item.from?.userId}
                style={{ marginTop: 12, borderRadius: 8 }}
                fit='cover'
                width={42}
                height={42}
              />}
            >
              <div className="briefInfoBar">
                {item.from?.userName || item.from?.nickName}
                {/* &gt; 林育 */}
                <div className="time">{moment(item.timestamp).format('HH:mm')}</div>
              </div>
              <div className="userMessage searchContent" dangerouslySetInnerHTML={{__html: xss(item.searchContent)}} />
            </List.Item>
          })}
        </List>
        <InfiniteScroll loadMore={getNextData} hasMore={pagination[SearchTypes.MESSAGE]?.totalPage > pagination[SearchTypes.MESSAGE]?.pageIndex} />
      </Tabs.Tab>
    </Tabs>
  </div>)
}